package mysql

import "gorm.io/gorm"

//商品表

type Goods struct {
	gorm.Model
	GoodsTitle  string `gorm:"type:varchar(50);not null;comment:商品标题"`
	GoodsPrice  int64  `gorm:"not null;comment:商品价格"`
	GoodsStock  int64  `gorm:"not null;comment:商品库存"`
	GoodsCover  string `gorm:"type:varchar(255);comment:商品封面"`
	GoodsStatus int8   `gorm:"not null;comment:商品状态"`
}

//商品创建

func (g *Goods) Create() error {
	return Db.Create(&g).Error
}

//列表

func (g *Goods) GoodsList(keyword string, page, size int) ([]*Goods, error) {
	var list []*Goods
	err = Db.Where("goods_title like ?", "%"+keyword+"%").Scopes(Paginate(page, size)).Order("goods_price desc,created_at desc").Find(&list).Error
	return list, err
}

// 分页

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

//商品详情

func (g *Goods) Details(goodsId int64) error {
	return Db.Where("id = ?", goodsId).First(&g).Error
}
